package com.wlyuan.open.scanner.application.handler.incr;

import com.wlyuan.open.dto.OpenTenantSyncDTO;
import com.wlyuan.open.scanner.assembler.ScannerTenantAssembler;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.repository.CompanyRepository;
import com.wlyuan.open.scanner.utils.enums.tenant.ShareCompanyTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Optional;

/**
 * @author lijing
 * @description 租户 增量 listener
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantIncrHandler extends BaseIncrHandler<OpenTenantSyncDTO> {
    private final CompanyRepository companyRepository;

    /**
     * 单个增量同步
     *
     * @param companyId
     */
    @Override
    public OpenTenantSyncDTO process(Long companyId) {
        logger.info("租户增量同步：{}", companyId);
        return Optional.ofNullable(companyId).map(tenantId -> {
            var company = companyRepository.getById(tenantId);
            //企业
            if (ShareCompanyTypeEnum.isCompany(company.getPersonal())) {
                var tenant = companyRepository.getCompanyTenantById(tenantId);
                return ScannerTenantAssembler.assemble(tenant);
            }
            //司机
            if (ShareCompanyTypeEnum.isPersonal(company.getPersonal())) {
                var tenant = companyRepository.getDriverTenantById(tenantId);
                return ScannerTenantAssembler.assembleDriver(tenant);
            }
            return null;
        }).orElse(null);
    }

    @Override
    public void incrByTenantId(Long tenantId) {

    }

    @Override
    public void incrByTime(Long tenantId, String startTime, String endTime) {
        var list = companyRepository.getByTime(startTime, endTime);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("根据时间{},{}数据为0", startTime, endTime);
            return;
        }
        logger.info("根据时间{},{}数据为：{}", startTime, endTime, list.size());
        list.parallelStream().forEach(id -> increment(id));
        logger.info("同步完成");
    }

    @Override
    public String getSyncType() {
        return ScannerCodeEnum.TENANT.getVal();
    }
}
